import type { Directive } from 'vue'
import { ElLoading } from 'element-plus'

// 加载指令
export const loading: Directive = {
  mounted(el, binding) {
    const { value } = binding
    
    if (value) {
      const loadingInstance = ElLoading.service({
        target: el,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      // 将loading实例存储到元素上
      el._loadingInstance = loadingInstance
    }
  },
  
  updated(el, binding) {
    const { value } = binding
    const loadingInstance = el._loadingInstance
    
    if (value && !loadingInstance) {
      const newLoadingInstance = ElLoading.service({
        target: el,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      el._loadingInstance = newLoadingInstance
    } else if (!value && loadingInstance) {
      loadingInstance.close()
      el._loadingInstance = null
    }
  },
  
  unmounted(el) {
    const loadingInstance = el._loadingInstance
    if (loadingInstance) {
      loadingInstance.close()
      el._loadingInstance = null
    }
  }
}
